package com.kaifamiao.wendao.filter;

import com.kaifamiao.wendao.entity.Customer;
import com.kaifamiao.wendao.entity.Topic;
import com.kaifamiao.wendao.service.CTRservice;
import com.kaifamiao.wendao.utils.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Set;

public class CollectFilter implements Filter {
    private Set<String> urls;
    CTRservice ctRservice=new CTRservice();

    @Override
    public void init(FilterConfig config) throws ServletException {
        urls = Set.of("/topic/collect");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpSession session=request.getSession();
        String uri = request.getRequestURI();
        // 确定当前被访问的资源是否属于需要被拦截
        if (urls.contains(uri)) {
            Object o= session.getAttribute(Constants.CUSTOMER_LOGINED);
            Customer customer=(Customer) o;
            String i=request.getParameter("id");
            Long tid=Long.valueOf(i);
            List<Topic> list=ctRservice.load(customer.getId());
            for (Topic topic : list) {

                if (tid.equals(topic.getId())){
                    session.setAttribute("switchs",false);
                    response.sendRedirect(request.getContextPath() + "/topic/collect/remove?id="+tid);
                    return;
                }
            }


        }

        // 继续向后传递请求和响应对象
        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {
    }
}
